package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
/*@Slf4j注解
* 1.日志注解
* 2.通过日志对象打印不同级别的日志*/
@Api(tags = "1.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    /*@RequestBody
    * 请求体,将前端发送来的数据转换为java语言格式*/
    /*1.注册功能*/
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        log.debug("userDTO="+userRegDTO);
        String username = userRegDTO.getUsername();
        /*1.接收客户端传递数据---若需要接受收据则需要创建dto接收
        * 2.校验数据合法性[暂时无需]
        * 3.确定用户名是否被占用[select]
        *   3.1被占用返回2
        *   3.2未被占用则[insert],返回1*/
        UserVO userVO = userMapper.selectByUsername(username);
        log.debug("userVO="+userVO);
        if (userVO!=null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO , user);
        userMapper.insert(user);
        return JsonResult.ok();
    }

    /*2.登录功能*/
    /*HttpSession 会话保持*/
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult userLogin(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if(userVO.getPassword().equals(userLoginDTO.getPassword())){
            session.setAttribute("user",userVO);
        return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    /*3.获取当前用户功能*/
    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        //内存中获取会话标识
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    /*4.退出登录功能*/
    @ApiOperation("退出登录")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        //删除会话标识
        session.removeAttribute("user");
    }
}
